import React, { Component } from 'react';
import { high, toast, cacheTools, promptBox } from 'nc-lightapp-front';
import {
	hrAjax as ajax,
	snCreateUIDom,
	getAppPageConfig,
	getQueryCondition,
	fixedCol
} from 'src/hrpub/common/utils/utils';
import deepCopy from 'src/hrpub/common/utils/deep-copy';
import Header from 'src/hrcm/contractmgt/terminate/main/components/header/index';
import MainTable from 'src/hrcm/contractmgt/terminate/main/components/mainTable/index';
import MainCard from 'src/hrcm/contractmgt/terminate/main/components/mainCard/index';
import NewIncreased from 'src/hrcm/public/components/NewIncreased/index';
const { appcode, pagecode } = getAppPageConfig();
import NCUploader from 'uap/common/components/NCUploader';

import './index.less';
const path = '/nccloud/hrcm/make/';
const commonPath = '/nccloud/hrcm/common/';
const reqData = [
	{
		rqUrl: '/platform/templet/querypage.do',
		rqJson: `{\n  \"pagecode\": \"60110303p\",\n  \"appcode\": \"60110303\"\n}`,
		rqCode: 'searchQuery'
	},
	{
		rqUrl: '/platform/templet/querypage.do',
		rqJson: `{\n  \"pagecode\": \"${pagecode}\",\n  \"appcode\": \"${appcode}\"\n}`,
		rqCode: 'template'
	},
	{
		rqUrl: '/platform/appregister/queryallbtns.do',
		rqJson: `{\n  \"pagecode\": \"${pagecode}\",\n  \"appcode\": \"${appcode}\"\n}`,
		rqCode: 'button'
	},
	{
		rqUrl: '/platform/appregister/queryappcontext.do',
		rqJson: `{\n  \"appcode\": \"${appcode}\"}`,
		rqCode: 'context'
	}
];
class Terminate extends Component {
	static propTypes = {};
	/* 默认属性 */
	static defaultProps = {
		from: 'terminate',
		appcode,
		pagecode,
		areaCode: {
			table: 'dataList',
			card: 'dataCard',
			add: 'dataCard_add',
			agreement: 'showAgreement'
		},
		URLS: {
			list: `${commonPath}QueryDataAction.do`,
			delete: `${path}MakeDeleteAction.do`,
			addModal: `${commonPath}DataInitAction.do`,
			editSave: `${path}UpdateSaveDataAction.do`,
			addSave: `${path}MakeAddSaveAction.do`,
			addSave2: `${path}MakeAddSaveActionAfter.do`,
			takeeffect: `${path}MakeEffectiveAction.do`,
			getFormMate: `${commonPath}QueryDataCardAction.do`
		}
	};
	constructor(props) {
		super(props);
		if (props.use) {
            props.use.form('dataCard', 'dataBefore', 'dataAfter', 'dataCard_add')
            props.use.editTable('dataList',  'psnList', 'chgPsnList') // 'showAgreement',
            props.use.search('listquery')
			props.use.table('showAgreement_add', 'showAgreement')
        }
		this.state = {
			showMode: 'list-browse', // card-browse,card-edit
			toEditFrom: '',
			showUploader: false,
			showAddModal: false,
			showAgreement: false,
			hasListData: false,
			pkOrg: null,
			cardViewId: null,
			billId: null,
			billNo: null,
			json: {},
			hrorgobj: null,
			searchData: {},
			pageid: ''
		};
		snCreateUIDom({ pagecode: props.pagecode, appcode: props.appcode }, reqData, (data) => {
			let temps = Object.assign({}, data.searchQuery, data.template);
			let buttons = data.button || {};
			let listItem = temps.dataList.items;
			let pageid = temps.pageid
			/* 固定表格栏位 */
			fixedCol(
				temps.dataList,
				[ 'contractnum', 'pk_majorcorp', 'pk_psndoc.code', 'pk_psndoc.name' ],
				this.state.json['cm6011-000152']
			);
			this.initTemplate.apply(this, [ listItem ]);
			// 复制一份详情页表格模板
			temps['dataCard_add'] = deepCopy(temps[props.areaCode.card]);
			temps['dataCard_add'].code = 'dataCard_add';
			temps['dataCard_add'].name = '另一个dataCard';
			props.meta.setMeta(temps);
			props.button.setButtons(buttons);
			this.setState({
				pageid
			})
		});

		this.refresh = this.refresh.bind(this);
		this.updateState = this.updateState.bind(this);
		this.onHideUploader = this.onHideUploader.bind(this);
		this.takeEffect = this.takeEffect.bind(this);
		this.save = this.save.bind(this);
		this.showUpolad = this.showUpolad.bind(this);
		this._tackEffect_ = this._tackEffect_.bind(this);
	}
	initTemplate(datas) {
		const { json } = this.state;

		datas.push(
			{
				attrcode: 'attachment',
				itemtype: 'customer',
				hyperlinkflag: false,
				label: json['cm6011-000062'] /* 国际化处理： 附件管理*/,
				width: '120px',
				textAlign: 'center',
				visible: true,
				fixed: 'right',
				render: (text, record, index) => {
					let billId = record.values.pk_psndoc_sub.value;
					let billNo = record.values.contractnum.value;
					return (
						<span className="btn-upload">
							<i
								className="icon iconfont icon-fujianshenpi"
								onClick={() => {
									this.checkDataPermission([ billId ], 'attachment', 'contract', () => {
										this.setState({
											showUploader: true,
											billId: billId,
											billNo: billNo
										});
									});
								}}
							/>
						</span>
					);
				}
			},
			{
				attrcode: 'handleArea',
				itemtype: 'customer',
				hyperlinkflag: false,
				label: json['cm6011-000064'],
				width: '180px',
				textAlign: 'center',
				visible: true,
				fixed: 'right',
				render: (text, record, index) => {
					return (
						<div>
							<span
								style={{ color: '#0073E1', cursor: 'pointer', marginRight: '12px' }}
								onClick={() => {
									const allpks = cacheTools.get('allpks');
									this.checkDataPermission(
										[ record.values['pk_psndoc_sub'].value ],
										'edit',
										'contract',
										() => {
											setTimeout(() => {
												this.setState(
													{
														showMode: 'card-edit',
														toEditFrom: 'list-browse',
														cardViewId: allpks[index]
													},
													() => {
														this.setFormData(text, record, index);
													}
												);
											}, 1000);
										}
									);
								}}
							>
								{json['cm6011-000067']}
							</span>
							<span
								style={{ color: '#0073E1', cursor: 'pointer', marginRight: '12px' }}
								onClick={this.deleteRow.bind(this, record)}
							>
								{json['cm6011-000065']}
							</span>
							{/* <span
								style={{ color: '#0073E1', cursor: 'pointer' }}
								onClick={this.takeEffect.bind(this, record, index)}
							>
								{json['cm6011-000071']}
							</span> */}
						</div>
					);
				}
			}
		);
		datas.forEach((item, index) => {
			if (item.attrcode === 'contractnum') {
				item.renderStatus = 'browse';
				item.className = 'contractnum';
				item.render = (value, record, index) => {
					const __text__ =
						record && record.values['contractnum'] && record.values['contractnum'].value
							? record.values['contractnum'].value
							: '___';
					return (
						<a
							href="#"
							onClick={(ev) => {
								ev.preventDefault();
								const allpks = cacheTools.get('allpks');
								setTimeout(() => {
									this.setState(
										{
											showMode: 'card-browse',
											cardViewId: allpks[index]
										},
										() => {
											this.setFormData(value, record, index);
										}
									);
								}, 1000);
							}}
						>
							{__text__}
						</a>
					);
				};
			}
		});
	}
	checkDataPermission(billPks, opFlag, nodeKey, callAction, params) {
		ajax({
			url: '/nccloud/hrcm/agreement/CheckDataPermissionAction.do',
			data: {
				billPks,
				opFlag,
				nodeKey
			},
			success: (res) => {
				callAction(params);
			}
		});
	}
	/* 上传组件打开 */
	showUpolad() {
		const { billId, billNo } = this.state;
		return (
			<NCUploader
				billId={billId}
				billNo={billNo}
				placement={'top'}
				onHide={this.onHideUploader} // 关闭功能
			/>
		);
	}
	// 关闭附件
	onHideUploader() {
		this.setState({
			showUploader: false
		});
	}
	// 行删除
	deleteRow(record) {
		const { pkOrg, json } = this.state;
		const { URLS } = this.props;
		this.checkDataPermission([ record.values['pk_psndoc_sub'].value ], 'delete', 'contract', () => {
			promptBox({
				color: 'warning',
				title: json['cm6011-000030'] /* 国际化处理： 提示*/,
				content: json['cm6011-000042'] /* 国际化处理： 您确定要删除选择数据吗*/,
				beSureBtnClick: () => {
					ajax({
						url: URLS.delete,
						data: {
							pk_org: pkOrg,
							modename: 'hi_psndoc_ctrt',
							isCard: false,
							allpks: [ record.values.pk_psndoc_sub.value ]
						},
						success: (res) => {
							this.refs.maintable.getTableData();
						}
					});
				}
			});
		});
	}
	/* 生效 */
	takeEffect(record) {
		const { editTable, areaCode, form } = this.props;
		const { json, showMode } = this.state;
		let params = {
			baseParam: {
				step: '0',
				info2: null
			},
			selectCtrtpks: [], // pk_psndoc_sub.value 合同主键
			selectedVcontractnums: [] //协议编号
		};
		if (showMode === 'card-browse') {
			let curData = form.getAllFormValue(areaCode.card);
			params.selectCtrtpks = curData.rows.map((item) => item.values.pk_psndoc_sub.value);
		} else {
			if (record) {
				params.selectCtrtpks.push(record.values.pk_psndoc_sub.value);
			} else {
				let sltRow = editTable.getCheckedRows(areaCode.table);
				if (!sltRow.length) {
					return toast({ color: 'danger', content: json['cm6011-000010'] }); /* 国际化处理 '请选择要操作的条目!' */
				} else {
					sltRow.forEach((item) => {
						params.selectCtrtpks.push(item.data.values.pk_psndoc_sub.value);
					});
				}
			}
		}
		this.checkDataPermission(params.selectCtrtpks, 'effect', 'contract', this._tackEffect_, params);
	}
	_tackEffect_(params) {
		const { json, showMode, cardViewId } = this.state;
		const { URLS, cardPagination, editTable, areaCode } = this.props;
		let _params_ = params;
		ajax({
			url: URLS.takeeffect,
			data: _params_,
			success: (res) => {
				if (res.data.step === '99') {
					if (showMode === 'card-browse') {
						let tbIndex = editTable
							.getAllData(areaCode.table)
							.rows.findIndex((item) => item.values.pk_psndoc_sub.value === cardViewId);
						editTable.deleteTableRowsByIndex(areaCode.table, tbIndex);
						let _allpks_ = cacheTools.get('allpks').filter((item) => item !== cardViewId);
						cacheTools.set('allpks', _allpks_);
						const nextpg = cardPagination.getNextCardPaginationId({ id: cardViewId });
						cardPagination.setCardPaginationId({ id: cardViewId, status: 3 });
						this.refs.header.handlePageInfoChange(this.props, nextpg, 1);
						this.updateState({
							cardViewId: nextpg
						});
						this.refs.maincard.resetState();
					} else {
						this.refs.maintable.getTableData();
						this.refs.maincard.resetState();
					}
				} else {
					promptBox({
						color: 'warning',
						title: json['cm6011-000030'] /* 国际化处理： 提示*/,
						content: res.data.msg,
						beSureBtnClick: () => {
							_params_.baseParam.step = res.data.step;
							_params_.baseParam.info2 = res.data.info2;
							if (res.data.step === '4') {
								this.refs.maincard.setShowAgreement(res.data, _params_);
							} else {
								this._tackEffect_(_params_);
							}
						},
						cancelBtnClick: () => {
							this.refs.maintable.getTableData();
						}
					});
				}
			}
		});
	}
	/* 编辑保存 */
	save() {
		this.refs.maincard.save();
	}
	/* update state function */
	updateState(data, callback = () => {}) {
		this.setState(data, callback);
	}
	componentWillMount() {
		// ajax请求时带出去系统参数
		const { appcode, pagecode } = this.props;
		let callback = (json, status, inlt) => {
			if (status) {
				this.setState({ json, inlt }); // 保存json和inlt到页面state中并刷新页面
			}
		};
		this.props.MultiInit.getMultiLang({ moduleId: 'cm6011', domainName: 'hrcm', callback });
	}

	/* 
        点击card页面中的返回
        更改showMode并重新获取数据
    */
	backToList() {
		this.updateState({ showMode: 'list-browse' }, () => {
			this.refs.maintable.getTableData();
		});
	}
	/* 刷新功能较特殊,所以写在根目录 */
	refresh() {
		const { pkOrg } = this.state;
		if (pkOrg) {
			this.refs.maintable.getTableData();
		} else {
			location.reload();
		}
	}
	/* 新增弹窗 */
	openAddModal() {
		const { pkOrg, showAddModal } = this.state;
		const { areaCode, form } = this.props;
		form.setFormStatus(areaCode.add, 'eidt');
		return (
			<NewIncreased
				{...this.props}
				setModalVisible={showAddModal}
				pkOrg={pkOrg}
				queryConditionParams={{ isIncludeCancelDept: 'true' }}
				onClose={this.closeAddModal.bind(this)}
				nextHandle={this.nextHandle.bind(this)}
				doneHandle={this.doneHandle.bind(this)}
			>
				{form.createForm(areaCode.add, {
					onAfterEvent: this.refs.maincard.afterEvent.bind(this)
				})}
			</NewIncreased>
		);
	}
	closeAddModal() {
		const { showMode } = this.state;
		this.setState({ showAddModal: false }, () => {
			if (showMode === 'list-browse') {
				this.refs.maintable.getTableData();
			} else {
				// this.refs.maincard.getFormData();
			}
		});
	}
	nextHandle(sltdt) {
		this.refs.maincard.nextHandle(sltdt);
	}
	doneHandle() {
		this.refs.maincard.done();
	}
	setFormData(value, recode, index) {
		this.refs.maincard.getFormData(value, recode, index);
	}
	toSearch(props) {
		let searchData = getQueryCondition(props, 'listquery');
		this.updateState(
			{
				searchData
			},
			() => {
				this.refs.maintable.getTableData();
			}
		);
	}
	render() {
		const { search } = this.props;
		const {
			hrorgobj,
			showMode,
			hasListData,
			cardViewId,
			pkOrg,
			showUploader,
			showAddModal,
			json,
			toEditFrom,
			oid,
			pageid
		} = this.state;
		return (
			<div className="main nc-bill-card">
				<Header
					ref="header"
					{...this.props}
					hasList={hasListData}
					updateState={this.updateState}
					cardViewId={cardViewId}
					pkOrg={pkOrg}
					refresh={this.refresh}
					takeEffect={this.takeEffect}
					checkDataPermission={this.checkDataPermission}
					save={this.save}
					showMode={showMode}
					json={json}
					hrorgobj={hrorgobj}
					toEditFrom={toEditFrom}
				/>
				<MainTable
					ref="maintable"
					json={json}
					updateState={this.updateState}
					{...this.props}
					{...this.state}
					pkOrg={pkOrg}
					showMode={showMode}
				/>
				<MainCard
					pageid={pageid}
					ref="maincard"
					{...this.props}
					showMode={showMode}
					pkOrg={pkOrg}
					updateState={this.updateState}
					cardViewId={cardViewId}
					json={json}
					tackEffect={this._tackEffect_}
				/>
				{/* 新增弹窗 */}
				{showAddModal && this.openAddModal()}
				{/* 附件管理 */}
				{showUploader && this.showUpolad()}
				{/* 查询modal */}
				<div style={{ display: 'none' }}>
					{search.NCCreateSearch('listquery', {
						clickSearchBtn: this.toSearch.bind(this)
					})}
				</div>
			</div>
		);
	}
}

export default Terminate;
